// 优惠券API服务
import { get, post } from './request.js';

// API基础路径 - 根据后端实际路径调整
const API_BASE = '/mobile';

// 获取所有优惠券列表
export const getAllCoupons = async () => {
	try {
		const response = await get(`${API_BASE}/coupons`);
		
		console.log('所有优惠券API响应:', response);
		
		// 检查响应结构 - 后端返回的是 AjaxResult.success(data)
		const responseData = response.data || response;
		
		if (responseData && Array.isArray(responseData)) {
			const convertedData = responseData.map(coupon => ({
				id: coupon.id,
				name: coupon.name || '优惠券',
				description: coupon.type || '暂无描述', // 使用type字段作为描述
				amount: coupon.preferentialMoney || 0,
				condition: `满${coupon.triggerMoney || 0}可用`,
				validStart: coupon.start || new Date().toISOString(),
				validEnd: coupon.end || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
				merchantId: coupon.mId || null,
				merchantName: '通用商家',
				status: 'unused', // 默认状态为待使用
				type: coupon.type || 'discount',
				image: '/static/coupon-default.png',
				discount: coupon.discount || null,
				triggerMoney: coupon.triggerMoney || 0,
				preferentialMoney: coupon.preferentialMoney || 0,
				num: coupon.num || 0,
				size: coupon.size || 0,
				expirationStart: coupon.expirationStart || null,
				expirationEnd: coupon.expirationEnd || null
			}));
			
			console.log('转换后的所有优惠券数据:', convertedData);
			
			return {
				success: true,
				data: convertedData,
				message: '获取成功'
			};
		}
		
		console.log('所有优惠券响应数据为空或格式不正确:', responseData);
		
		return {
			success: true,
			data: [],
			message: '获取成功'
		};
	} catch (error) {
		console.error('获取优惠券列表失败:', error);
		return {
			success: false,
			data: [],
			message: '获取失败：' + (error.message || '网络错误')
		};
	}
};

// 获取用户已领取的优惠券列表
export const getUserCoupons = async (userId, status = 'all') => {
	try {
		console.log('获取用户优惠券: userId=', userId, 'status=', status);
		
		// 尝试多个可能的API路径
		let response;
		
		try {
			response = await get(`${API_BASE}/user-coupons?userId=${userId}`);
		} catch (error) {
			console.log('主要用户优惠券API路径失败，尝试备用路径');
			try {
				response = await get(`${API_BASE}/coupons/user?userId=${userId}`);
			} catch (error2) {
				console.log('备用用户优惠券API路径也失败，尝试备用路径2');
				try {
					response = await get(`${API_BASE}/my-coupons?userId=${userId}`);
				} catch (error3) {
					console.log('备用用户优惠券API路径2也失败，尝试备用路径3');
					try {
						response = await get(`${API_BASE}/user/coupons?userId=${userId}`);
					} catch (error4) {
						console.log('备用用户优惠券API路径3也失败，尝试备用路径4');
						try {
							response = await get(`${API_BASE}/coupons?userId=${userId}`);
						} catch (error5) {
							console.log('所有用户优惠券API路径都失败，返回空数据');
							// 返回模拟数据结构，避免页面崩溃
							return {
								code: 200,
								msg: "暂无优惠券数据",
								data: []
							};
						}
					}
				}
			}
		}
		
		console.log('用户优惠券API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: [...]}
		return response;
	} catch (error) {
		console.error('获取用户优惠券失败:', error);
		// 返回模拟数据结构，避免页面崩溃
		return {
			code: 200,
			msg: "获取失败，使用模拟数据",
			data: []
		};
	}
};

// 获取可领取的优惠券列表
export const getAvailableCoupons = async () => {
	try {
		// 尝试多个可能的API路径
		let response;
		
		try {
			response = await get(`${API_BASE}/coupons/available`);
		} catch (error) {
			console.log('主要可领取优惠券API路径失败，尝试备用路径');
			try {
				response = await get(`${API_BASE}/coupons`);
			} catch (error2) {
				console.log('备用可领取优惠券API路径也失败，尝试备用路径2');
				try {
					response = await get(`${API_BASE}/coupons/list`);
				} catch (error3) {
					console.log('备用可领取优惠券API路径2也失败，尝试备用路径3');
					try {
						response = await get(`${API_BASE}/available-coupons`);
					} catch (error4) {
						console.log('备用可领取优惠券API路径3也失败，尝试备用路径4');
						try {
							response = await get(`${API_BASE}/coupons/center`);
						} catch (error5) {
							console.log('所有可领取优惠券API路径都失败，返回空数据');
							// 返回模拟数据结构，避免页面崩溃
							return {
								code: 200,
								msg: "暂无可领取优惠券",
								data: []
							};
						}
					}
				}
			}
		}
		
		console.log('优惠券API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: [...]}
		return response;
	} catch (error) {
		console.error('获取可领取优惠券失败:', error);
		// 返回模拟数据结构，避免页面崩溃
		return {
			code: 200,
			msg: "获取失败，使用模拟数据",
			data: []
		};
	}
};

// 根据商家ID获取优惠券
export const getCouponsByMerchant = async (merchantId) => {
	try {
		const response = await get(`${API_BASE}/coupons/merchant/${merchantId}`);
		
		console.log('商家优惠券API响应:', response);
		
		// 检查响应结构 - 后端返回的是 AjaxResult.success(data)
		const responseData = response.data || response;
		
		if (responseData && Array.isArray(responseData)) {
			const convertedData = responseData.map(coupon => ({
				id: coupon.id,
				name: coupon.name || '优惠券',
				description: coupon.type || '暂无描述', // 使用type字段作为描述
				amount: coupon.preferentialMoney || 0,
				condition: `满${coupon.triggerMoney || 0}可用`,
				validStart: coupon.start || new Date().toISOString(),
				validEnd: coupon.end || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
				merchantId: coupon.mId || merchantId,
				merchantName: '商家优惠券',
				status: coupon.status || 'available',
				type: coupon.type || 'discount',
				image: '/static/coupon-default.png',
				discount: coupon.discount || null,
				triggerMoney: coupon.triggerMoney || 0,
				preferentialMoney: coupon.preferentialMoney || 0,
				num: coupon.num || 0,
				size: coupon.size || 0,
				expirationStart: coupon.expirationStart || null,
				expirationEnd: coupon.expirationEnd || null
			}));
			
			console.log('转换后的商家优惠券数据:', convertedData);
			
			return {
				success: true,
				data: convertedData,
				message: '获取成功'
			};
		}
		
		console.log('商家优惠券响应数据为空或格式不正确:', responseData);
		
		return {
			success: true,
			data: [],
			message: '获取成功'
		};
	} catch (error) {
		console.error('获取商家优惠券失败:', error);
		return {
			success: false,
			data: [],
			message: '获取失败：' + (error.message || '网络错误')
		};
	}
};

// 领取优惠券
export const receiveCoupon = async (couponId, userId) => {
	try {
		console.log('开始领取优惠券:', { couponId, userId });
		
		const response = await post(`${API_BASE}/coupons/${couponId}/receive`, {
			userId: userId
		});
		
		console.log('领取优惠券API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: {...}}
		return response;
	} catch (error) {
		console.error('领取优惠券失败:', error);
		throw error;
	}
};

// 使用优惠券
export const useCoupon = async (couponId, userId) => {
	try {
		console.log('开始使用优惠券:', { couponId, userId });
		
		const response = await post(`${API_BASE}/coupons/${couponId}/use`, {
			userId: userId
		});
		
		console.log('使用优惠券API响应:', response);
		
		// 根据你的request.js，这里直接返回后端AjaxResult对象
		// 后端返回格式：{code: 200, msg: "操作成功", data: {...}}
		return response;
	} catch (error) {
		console.error('使用优惠券失败:', error);
		throw error;
	}
};

// 获取模拟优惠券数据
export const getMockCoupons = async () => {
	// 模拟API调用延迟
	await new Promise(resolve => setTimeout(resolve, 500));
	
	const mockData = [
		{
			id: 1,
			name: '满100减20券',
			description: '满减券，满100元可用',
			amount: 20,
			condition: '满100可用',
			validStart: '2025-08-01',
			validEnd: '2025-08-31',
			merchantName: '通用商家',
			status: 'available',
			type: 'discount',
			image: '/static/coupon-default.png'
		},
		{
			id: 2,
			name: '9折优惠券',
			description: '全场9折优惠',
			amount: 0,
			condition: '无门槛',
			validStart: '2025-08-01',
			validEnd: '2025-08-31',
			merchantName: '通用商家',
			status: 'available',
			type: 'discount',
			image: '/static/coupon-default.png'
		}
	];
	
	return {
		success: true,
		data: mockData,
		message: '获取模拟数据成功'
	};
}; 

// 获取优惠券统计信息
export const getCouponStats = async (userId) => {
	try {
		console.log('获取优惠券统计: userId=', userId);
		
		// 获取所有优惠券数据
		const response = await get(`${API_BASE}/coupons`);
		const responseData = response.data || response;
		
		if (responseData && Array.isArray(responseData)) {
			// 计算统计信息
			const totalCount = responseData.length;
			const availableCount = responseData.filter(coupon => 
				coupon.status === 0 || coupon.status === 'available'
			).length;
			const usedCount = responseData.filter(coupon => 
				coupon.status === 1 || coupon.status === 'used'
			).length;
			const expiredCount = responseData.filter(coupon => 
				coupon.status === 2 || coupon.status === 'expired'
			).length;
			
			const stats = {
				total: totalCount,
				available: availableCount,
				used: usedCount,
				expired: expiredCount
			};
			
			console.log('优惠券统计结果:', stats);
			
			return {
				success: true,
				data: stats,
				message: '获取成功'
			};
		}
		
		return {
			success: true,
			data: { total: 0, available: 0, used: 0, expired: 0 },
			message: '获取成功'
		};
	} catch (error) {
		console.error('获取优惠券统计失败:', error);
		return {
			success: false,
			data: { total: 0, available: 0, used: 0, expired: 0 },
			message: '获取失败：' + (error.message || '网络错误')
		};
	}
}; 